package com.asia5b.a5mall.middleware.config

import android.content.Context
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5mall.middleware.R
import com.asia5b.a5mall.middleware.api.ApiManager.API_MEMBER
import com.asia5b.a5mall.middleware.model.member.MemberCountModel
import com.asia5b.a5mall.middleware.model.member.MemberModel
import com.asia5b.a5mall.middleware.utils.JsonUtil.anyToJson
import com.asia5b.a5mall.middleware.utils.PreferenceHelper
import com.asia5b.a5mall.middleware.utils.showMessage
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import timber.log.Timber

/**
 * Created by zhangyuncai on 2020/5/28.
 * 全局持有一个用户,方便维护
 */
object UserRepository {
    private val userInfoSubject by lazy { PublishSubject.create<MemberModel>(); }
    private val memberApi by lazy { API_MEMBER; }

    var cacheUserInfo: MemberModel
        get() {
            return PreferenceHelper.seriToMember()
        }
        set(value) {
            PreferenceHelper.memberToSeri(value)
        }


    private val inboxCountSubject by lazy { PublishSubject.create<MemberCountModel>(); }

    fun getUserInfoOB(): Flowable<MemberModel> {
        return userInfoSubject.toFlowable(BackpressureStrategy.LATEST);
    }

    fun getInboxOB(): Flowable<MemberCountModel> {
        return inboxCountSubject.toFlowable(BackpressureStrategy.LATEST);
    }

    fun setUserInfo(userInfo: MemberModel?, isToast: Boolean? = null) {
        if (userInfo == null) {
            cacheUserInfo = MemberModel()
            Timber.d("--->>>>>>>>---用户登出")
        } else {
            isToast?.run {
                showMessage(ResString.get(R.string.登录成功))
            }
            cacheUserInfo = userInfo
            Timber.d("--->>>>>>>>---登录用户信息" + anyToJson(userInfo))
        }
    }

    fun getUserInfo(): MemberModel {
        return cacheUserInfo
    }

    /**
     * 是否是登录状态
     */
    fun isLogin(context: Context? = null): Boolean {
        if (cacheUserInfo.member_id > 0) {//只需要拥有user_id,个人信息就不是空
            return true
        } else {
            context?.run {
                ARouter.getInstance().build(ActCons.LoginActivity).withTransition(R.anim.push_left_in, R.anim.push_left_out).navigation(context)
            }
            return false
        }
    }

    /**
     * 从服务器更新用户资料
     */
    fun updateUserInfo() {
        getUserInfoByNet()
    }

    private fun getUserInfoByNet() {
        if (!isLogin()) {
            Timber.d("--->>>>>>>>---没登录")
            return
        }
        memberApi.memberInfo()
                .subscribeOn(Schedulers.io())
                .subscribe({ userInfo: MemberModel ->
                    //仅仅更新UserInfo,不涉及到登录/退出
                    setUserInfo(userInfo)
                    userInfoSubject.onNext(userInfo)
                }) { throwable: Throwable -> throwable.printStackTrace() }
    }

    /**
     * 从服务器更新用户资料
     */
    fun updateInboxCount() {
        getInboxInfoByNet()
    }

    fun getInboxInfoByNet() {
        if (!isLogin()) {
            Timber.d("--->>>>>>>>---没登录")
            inboxCountSubject.onNext(MemberCountModel())
            return
        }
        memberApi.getMemberOther()
                .subscribeOn(Schedulers.io())
                .subscribe({ memberCountModel: MemberCountModel? ->
                    if (memberCountModel != null) {
                        inboxCountSubject.onNext(memberCountModel)
                    }
                }) { throwable: Throwable -> throwable.printStackTrace() }
    }

    fun setNums(textView: TextView, num: Int) {
        textView.visibility = if (num <= 0) View.INVISIBLE else View.VISIBLE
        textView.text = if (num > 99) "99+" else num.toString() + ""
    }
}